package com.daidai.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Author: Mr.Chen
 * Date: 2022/07/31 15:45
 * Description: 图片处理
 */
public class PicUtil {
    public static String pictureUtil(String base64Data, HttpServletRequest httpServletRequest) {
        String dataPrix = "";
        String data = "";

        String[] split = base64Data.split("base64,");
        if (split.length == 2) {
            dataPrix = split[0];
            data = split[1];
        }

        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            suffix = ".png";
        }
        String tempFileName = UUID.randomUUID() + suffix;

        byte[] bytes = Base64Utils.decodeFromString(data);
        String url = httpServletRequest.getSession().getServletContext().getRealPath("/upload");

        try {
            FileUtils.writeByteArrayToFile(new File(url + "/" + tempFileName), bytes);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

        String picture = "../upload/" + tempFileName;

        return picture;
    }

}
